<template>
  <Navbar :title="'点餐'"></Navbar>
  <div class="order-wrap">
    <!-- 侧边导航栏 -->
    <div class="van-sidebar">
      <van-sidebar v-model="active" @change="onChange">
        <van-sidebar-item
          v-for="item in items"
          :key="item.id"
          :title="item.text"
        />
      </van-sidebar>
    </div>
    <!-- 右侧商品区域 -->
    <div class="foods-wrap">
      <ul>
        <h1 class="title">{{ nowTitle }}</h1>
        <li class="food-item" v-for="(food, index) in nowFoods" :key="index">
          <div class="icon">
            <img :src="food.pic" alt="" />
          </div>
          <div class="content">
            <h2 class="name">{{ food.title }}</h2>
            <div class="price">￥{{ food.price.toFixed(2) }}</div>
          </div>
          <div class="button">
            <van-button
              v-if="food.did == 2"
              class="my-btn"
              @click="choseDetail(food.sid)"
              >选规格</van-button
            >
            <van-button
              v-if="food.did == 1"
              class="my-btn"
              @click="choseDetail(food.sid)"
              >选口味</van-button
            >
            <van-button
              v-if="food.did == 0"
              class="my-add"
              @click="add(food.title, food.price, 1)"
              >+</van-button
            >
          </div>
        </li>
      </ul>
    </div>

    <!-- 选规格弹出框 -->
    <div class="van-popup">
      <van-popup
        v-model:show="showpop"
        class="detail-pop"
        :style="{
          height: '68%',
          width: '92%',
          borderRadius: '10px',
        }"
      >
        <div class="flex-center">
          <van-image class="show-img" :src="chosenFood.pic"></van-image>
        </div>
        <p class="title">{{ chosenFood.title }}</p>
        <div class="tem-sur">
          <p class="sub-title" v-if="choseTem.length !== 0">温度</p>
          {{ chooseFood }}
          <div class="btn-group">
            <div v-for="(tem, index) in choseTem" :key="index">
              <button
                class="chose-btn"
                :class="checkedTem == index ? 'chosen-btn' : ''"
                @click="chooseTemp(index)"
              >
                {{ tem }}
              </button>
            </div>
          </div>
          <p class="sub-title" v-if="choseSurgar.length !== 0">甜度</p>
          <div class="btn-group">
            <div v-for="(sur, index) in choseSurgar" :key="index">
              <button
                class="chose-btn"
                :class="checkedSugar == index ? 'chosen-btn' : ''"
                @click="chooseSurgar(index)"
              >
                {{ sur }}
              </button>
            </div>
          </div>
        </div>

        <van-divider hairline="false" />
        <div class="show-detail">
          <div>
            <p class="show-price">¥{{ chosenFood.price.toFixed(2) }}</p>
            <p
              v-if="choseSurgar.length !== 0 || choseTem.length !== 0"
              class="show-chosen"
            >
              已选:{{ choseTem[checkedTem]
              }}<span v-if="tem !== '' && sugar !== ''">/</span
              >{{ choseSurgar[checkedSugar] }}
            </p>
          </div>
          <!-- 购物器的步进器 -->
          <div class="stepper">
            <van-stepper
              v-model="count"
              theme="round"
              button-size="22"
              disable-input
            />
          </div>
        </div>
        <div class="button">
          <button
            class="show-large-btn"
            type="primary"
            @click="
              choseok(
                chosenFood.title,
                count,
                chosenFood.price,
                choseTem[checkedTem],
                choseSurgar[checkedSugar],
                chosenFood.pic
              )
            "
          >
            选好了
          </button>
        </div>
      </van-popup>
    </div>

    <!-- 购物车投标，没有物品时不显示 -->
    <div v-if="totalprice !== 0" class="choseok">
      <div class="icon-info">
        <img src="../assets/image/shopcart.jpg" alt="" @click="CartDetail()" />
        <span class="total">￥{{ totalprice.toFixed(2) }}</span>
      </div>
      <button @click="goShopping()" class="goShopping">
        <span>去结算</span>
      </button>
    </div>
    <!-- 购物车详情 -->
    <div
      v-if="(ok == 0) & (totalprice !== 0)"
      class="cartDetail"
      :style="height"
    >
      <div>
        <van-swipe-cell>
          <!--购物车详情头-->
          <van-cell
            :border="false"
            class="showCartDetail"
            title="已选中的商品"
            value="清空购物车"
            @click="clear()"
          />
        </van-swipe-cell>
      </div>
      <div v-for="(cart, index) in shopList" :key="index">
        <!--购物车详情-->
        <van-grid
          direction="horizontal"
          :border="true"
          :column-num="4"
          class="cardetailitem"
          :gutter="-2"
        >
          <van-grid-item class="title">
            {{ cart.title }}
          </van-grid-item>
          <van-grid-item class="cartTotal"> ¥{{ cart.price }} </van-grid-item>
          <van-grid-item class="cartDetail-center">
            {{ cart.temp
            }}<span v-if="cart.temp !== undefined && cart.sugar !== undefined"
              >/</span
            >{{ cart.sugar }}
          </van-grid-item>
          <van-grid-item>
            <van-button
              class="cart-btn"
              @click="
                minus(
                  index,
                  cart.title,
                  cart.count,
                  cart.price,
                  cart.temp,
                  cart.sugar,
                  cart.pic
                )
              "
              >-</van-button
            >
            {{ cart.count }}
            <van-button
              class="cart-btn"
              @click="
                plus(
                  index,
                  cart.title,
                  cart.count,
                  cart.price,
                  cart.temp,
                  cart.sugar,
                  cart.pic
                )
              "
              >+</van-button
            >
          </van-grid-item>
        </van-grid>
      </div>
    </div>
  </div>
  <Tabbar></Tabbar>
</template>

<script>
import axios from "../utils/axios";
import { reactive, toRefs } from "@vue/reactivity";
import Navbar from "../components/Navbar.vue";
import Tabbar from "../components/Tabbar.vue";
import { onBeforeMount, onMounted } from "@vue/runtime-core";
import { Toast } from "vant";
import { useRouter } from "vue-router";
import { Dialog } from "vant";
export default {
  setup() {
    const router = useRouter();
    const state = reactive({
      uid: "",
      items: [
        //侧标导航的内容
        { text: "热销", id: 0 },
        { text: "新品推荐", id: 1 },
        { text: "冰淇淋与茶", id: 2 },
        { text: "真果茶", id: 3 },
        { text: "奶盖茶&原叶茶", id: 4 },
        { text: "奶茶&特饮", id: 5 },
        { text: "雪王提醒", id: 6 },
      ],
      active: 0, //当前选的左侧导航栏
      allFoods: [], //总商品
      nowFoods: [], //当前商品
      nowTitle: "热销",
      showpop: false,
      showDetail: true, //显示购物车
      chosenFood: {},
      choseTem: [],
      choseSurgar: [],
      checkedTem: 0,
      checkedSugar: 0,
      count: 1,
      totalprice: 0,
      shopList: [],
      height: 0,
      ok: 1,
    });

    //获取商品列表
    const getfoodData = () => {
      axios.get("/shop").then((res) => {
        // console.log(res.data.result);
        state.allFoods = res.data.result;
        state.nowFoods = res.data.result.filter((item) => item.lid == 0);
      });
    };

    //获取物品详情
    const getfoodDetail = (id) => {
      axios
        .get("/shopdetail", {
          params: {
            sid: id,
          },
        })
        .then((res) => {
          // console.log(res.data.result);
          const chose = res.data.result;
          chose.map((item) => {
            if (item.temp !== "") {
              state.choseTem.push(item.temp);
            }
            if (item.sugar !== "") {
              state.choseSurgar.push(item.sugar);
            }
          });
        });
    };

    //左侧导航栏点击事件
    const onChange = (index) => {
      // console.log(123, index, state.active);
      state.nowFoods = state.allFoods.filter(
        (item) => item.lid == state.active
      );
      state.nowTitle = state.items[index].text;
      // console.log(state.nowFoods);
    };

    const choseDetail = (id) => {
      // console.log(id);
      state.chosenFood = state.allFoods[id - 1];
      state.showpop = true;
      state.choseTem = [];
      state.choseSurgar = [];
      state.checkedTem = 0;
      state.checkedSugar = 0;
      getfoodDetail(id);
    };

    //选择温度
    const chooseTemp = (i) => {
      console.log(i);
      state.checkedTem = i;
    };

    //选择甜度
    const chooseSurgar = (i) => {
      console.log(i);
      state.checkedSugar = i;
    };

    //选好了
    const choseok = (title, count, price, temp, sugar, pic) => {
      state.showpop = false;
      // console.log(title, count, price, temp, sugar, pic);
      if (window.localStorage.getItem("userinfo") == null) {
        Toast.fail("请先登录");
        setTimeout(() => {
          router.push("/login");
        }, 1000);
      } else {
        state.uid = JSON.parse(window.localStorage.getItem("userinfo")).uid;
        let shopdetail = {};
        shopdetail.uid = state.uid;
        shopdetail.title = title;
        shopdetail.price = price;
        shopdetail.count = count;
        shopdetail.temp = temp;
        shopdetail.sugar = sugar;
        shopdetail.pic = pic;
        state.totalprice += count * price;
        // console.log(state.totalprice);
        if (window.localStorage.getItem("shopCart") == null) {
          window.localStorage.setItem(
            "shopCart",
            JSON.parse(JSON.stringify("[]"))
          );
          state.shopList = eval(
            "(" + window.localStorage.getItem("shopCart") + ")"
          );
          state.shopList.push(shopdetail);
          window.localStorage.setItem(
            "shopCart",
            JSON.stringify(this.shopList)
          );
        } else {
          state.shopList = eval(
            "(" + window.localStorage.getItem("shopCart") + ")"
          );
          state.shopList.push(shopdetail);
          window.localStorage.setItem(
            "shopCart",
            JSON.stringify(state.shopList)
          );
        } //默认count
        // 购物车高度
        state.height = 80 * state.shopList.length;
        setTimeout(() => {
          state.count = 1;
        }, 1000);
      }
    };
    // 加入购物车
    const add = (title, price, count) => {
      // console.log(title, price, count);
      const shopdetail = {};
      shopdetail.uid = state.uid;
      shopdetail.title = title;
      shopdetail.price = price;
      shopdetail.count = count;
      state.totalprice += price * count;
      state.shopList = eval(
        "(" + window.localStorage.getItem("shopCart") + ")"
      );
      state.shopList.push(shopdetail);
      window.localStorage.setItem("shopCart", JSON.stringify(state.shopList));
    };

    //点击购物车icon是否显示购物车详情
    const CartDetail = () => {
      state.showDetail = true;
      if (state.ok == 0) {
        state.ok = 1;
      } else {
        state.ok = 0;
      }
    };

    //增加购物车单个商品的数量
    const plus = (index, title, count, price, temp, sugar, pic) => {
      //购物车的+
      count += 1;
      let shopdetail = {};
      shopdetail.uid = state.uid;
      shopdetail.title = title;
      shopdetail.price = price;
      shopdetail.count = count;
      shopdetail.temp = temp;
      shopdetail.sugar = sugar;
      shopdetail.pic = pic;
      state.shopList.splice(index, 1, shopdetail);
      state.totalprice += price;
      window.localStorage.setItem("shopCart", JSON.stringify(state.shopList));
    };

    //减少购物车里单个商品数量
    const minus = (index, title, count, price, tem, sugar, pic) => {
      //购物车的-
      if (count == 1) {
        state.shopList.splice(index, 1);
        window.localStorage.setItem("shopCart", JSON.stringify(state.shopList));
      } else if (count > 1) {
        count--;
        let shopdetail = {};
        shopdetail.uid = state.uid;
        shopdetail.title = title;
        shopdetail.price = price;
        shopdetail.count = count;
        shopdetail.tem = tem;
        shopdetail.sugar = sugar;
        shopdetail.pic = pic;
        state.shopList.splice(index, 1, shopdetail);
        window.localStorage.setItem("shopCart", JSON.stringify(state.shopList));
      }
      state.totalprice -= price;
    };
    //清空购物车
    const clear = () => {
      Dialog.confirm({
        message: "确定清空购物车？",
      })
        .then(() => {
          // on confirm
          state.shopList = window.localStorage.setItem(
            "shopCart",
            JSON.parse(JSON.stringify("[]"))
          );
          state.totalprice = 0;
          state.ok = 0;
        })
        .catch(() => {
          // on cancel
        });
    };
    //去结算按钮
    const goShopping = () => {
      // console.log(state.shopList);
      axios.post("addShopCart", state.shopList).then((res) => {
        if (res.data.code == 200) {
          router.push({
            path: "/payment",
            // query: {
            //   totalprice: state.totalprice
            // },
          });
          window.localStorage.setItem("totalprice", state.totalprice);
        } else {
          Toast.fail("状态错误");
        }
      });

      // setTimeout(() => {
      //   //去结算后删除该用户购物车信息
      //   window.localStorage.removeItem("shopCart");
      // }, 1000);
    };
    // 在挂载之前先拿到localstorage的shopCart初始化一下
    onBeforeMount(() => {
      getfoodData();
      state.uid = JSON.parse(window.localStorage.getItem("userinfo")).uid;
      state.shopList = eval(
        "(" + window.localStorage.getItem("shopCart") + ")"
      );
    });

    onMounted(() => {
      if (window.localStorage.getItem("shopCart") == null) {
        window.localStorage.setItem(
          "shopCart",
          JSON.parse(JSON.stringify("[]"))
        );
      }
      if (window.sessionStorage.getItem("isPay") == "true") {
        window.localStorage.setItem(
          "shopCart",
          JSON.parse(JSON.stringify("[]"))
        );
      }
      state.shopList = eval(
        "(" + window.localStorage.getItem("shopCart") + ")"
      );
      state.shopList.forEach((item) => {
        state.totalprice += item.price * item.count;
      });
    });
    return {
      ...toRefs(state),
      onChange,
      getfoodData,
      getfoodDetail,
      choseDetail,
      chooseTemp,
      chooseSurgar,
      choseok,
      add,
      CartDetail,
      plus,
      minus,
      clear,
      goShopping,
    };
  },
  components: {
    Navbar,
    Tabbar,
  },
};
</script>

<style lang="less" scoped>
.order-wrap {
  display: flex;
  position: absolute;
  top: 46px;
  bottom: 46px;
  width: 100%;
  overflow: hidden;
  .van-sidebar {
    flex: 0 0 80px;
    background: #f3f5f7;
  }
  .foods-wrap {
    flex: 1;
    overflow: auto;
    .title {
      padding-left: 14px;
      margin-top: 0;
      height: 26px;
      line-height: 26px;
      border-left: 2px solid #d9dde1;
      font-size: 12px;
      color: #93999f;
      background: #f3f5f7;
    }
    .food-item {
      display: flex;
      margin: 18px;
      position: relative;
      .icon {
        margin-right: 10px;
        img {
          width: 80px;
          height: 80px;
        }
      }
      .content {
        width: 80px;
        .name {
          margin: 8px 0;
          height: 14px;
          line-height: 20px;
          font-size: 14px;
          color: #07111b;
        }
        .price {
          margin-top: 30px;
          color: #ffa511;
          font-size: 18px;
        }
      }
      .button {
        margin-top: 45px;
        .my-btn {
          font-size: 12px;
          color: #fff;
          height: 25px;
          background: #e50055;
          border-radius: 15px;
        }
        .my-add {
          margin-left: 45px;
          width: 20px;
          height: 20px;
          line-height: 20px;
          border-radius: 50%;
          color: #fff;
          padding: 0;
          background-color: #e50055;
        }
      }
    }
    .food-item:last-child {
      margin-bottom: 60px;
    }
  }
  .van-popup {
    .detail-pop {
      .flex-center {
        display: flex;
        justify-content: center;
        .show-img {
          width: 180px;
          height: 180px;
          margin-top: 20px;
        }
      }
      .title {
        /*遮罩层商品标题*/
        font-size: 18px;
        font-weight: 400;
        margin: 10px 0px 5px 10px;
      }
      .tem-sur {
        .sub-title {
          /*温度和糖度的字体*/
          font-size: 16px;
          margin: 5px 10px;
        }
        .btn-group {
          display: flex;
          flex-wrap: wrap;
          .chose-btn {
            /*遮罩层口味按钮*/
            font-size: 16px;
            color: #707070;
            width: 100px;
            background-color: #f8f8f8;
            padding: 8px 8px;
            border: 1px solid #d0d0d0;
            border-radius: 5px;
            margin: 3px 5px;
          }
          .chosen-btn {
            /*遮罩层被选按钮*/
            color: #fff;
            background-color: #e50055;
          }
        }
      }

      .show-detail {
        display: flex;
        justify-content: space-between;
        .show-price {
          font-size: 18px;
          padding-left: 10px;
        }
        .show-chosen {
          font-size: 14px;
          color: #b0b0b0;
          padding: 5px;
        }
        .stepper {
          margin-right: 20px;
          margin-top: 10px;
        }
      }
      .button {
        display: flex;
        justify-content: center;
        .show-large-btn {
          padding: 10px 8px;
          color: #fff;
          width: 90%;
          border-radius: 25px;
          background-color: #e50055;
          border: 0;
          margin: 5px 0px;
        }
      }
    }
  }
  .choseok {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #f0f0f0;
    width: 375px;
    z-index: 1000;
    position: fixed;
    bottom: 50px;
    .icon-info {
      width: 40px;
      height: 40px;
      margin: 5px 10px;
      display: flex;
      img {
        width: 40px;
        height: 40px;
      }
      .total {
        height: 40px;
        line-height: 40px;
        margin-left: 10px;
      }
    }
    .goShopping {
      z-index: 1000;
      color: #fff;
      background: #e50055;
      width: 100px;
      height: 50px;
      border: 0;
      border-radius: 3px;
      span {
        line-height: 50px;
        font-size: 20px;
        margin-right: 12px;
      }
    }
  }
  .cartDetail {
    width: 100%;
    bottom: 100px;
    position: fixed;
    font-size: 12px;
    .showCartDetail {
      background-color: #ededed;
      color: #000000;
      padding: 8px;
      .cardetailitem {
        height: 30px;
      }
    }
    .cartTotal {
      color: #ffa511;
      font-size: 18px;
      flex-basis: 16% !important;
    }
    .cartDetail-center {
      flex-basis: 28% !important;
    }
    .cart-btn {
      width: 20px;
      height: 20px;
      border-radius: 50%;
      color: #fff;
      padding: 0;
      background-color: #e50055;
      margin: 0 10px;
      align-items: center;
    }
  }
}
</style>